package com.leon.raw_consumer.tool;


import com.leon.rpc.JSONSerializer;
import com.leon.rpc.RpcDecoder;
import com.leon.rpc.RpcEncoder;
import com.leon.rpc.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {
    private static ExecutorService executor =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private static UserClientHandler client;

    // 针对每个远处服务创建一个代理对象（实际上应该创建一个单例的代理对象）
    public Object createProxy(final Class<?> serviceClass, final RpcRequest request) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                        new Class<?>[]{serviceClass}, (proxy, method, args) -> {

                    if (client == null) {
                        initClient();
                    }

                    request.setParameters(args);
                    request.setMethodName(method.getName());

                    // 填充参数类型数组，方便服务端根据方面名称和参数类型列表通过反射进行方法的定位和调用
                    Class[] types = new Class[args.length];
                    for (int i = 0; i < args.length; i++) {
                        types[i] = args[i].getClass();
                    }
                    request.setParameterTypes(types);
                    client.setRpcRequest(request);

                    RpcRequest ret = (RpcRequest) executor.submit(client).get();
                    return ret.getResult();
                });
    }

    private static void initClient() {
        client = new UserClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        /*p.addLast(new StringDecoder());
                        p.addLast(new StringEncoder());*/
                        p.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        p.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        p.addLast(client);
                    } });

        try {
            b.connect("localhost", 8989).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
